package com.csdj.server.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.csdj.server.pojo.Employee;
import com.csdj.server.pojo.MailConstants;
import com.csdj.server.pojo.MailLog;
import com.csdj.server.service.IEmployeeService;
import com.csdj.server.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author zyq
 * @Date 2023/2/3 10:34
 * @ClassName: MailTask
 * @Description:  消息发送 重试的定时任务
 * @Version 1.0
 */
@Component
public class MailTask {

    @Autowired
    private IMailLogService mailLogService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IEmployeeService employeeService;

    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTask(){
       //查询 数据表中 的消息日志
        //select * from t_mail_log where status=0 and tryTime<''
        List<MailLog> list = mailLogService.list(new QueryWrapper<MailLog>()
                .eq("status", 0)
                .lt("tryTime", LocalDateTime.now()));
        //循环 消息日志
        list.forEach(mailLog -> {
            //如果消息重试次数 大于等于3次
           if(mailLog.getCount()>=3){
               //更新的消息的状态 为发送失败
                mailLogService.update(new UpdateWrapper<MailLog>()
                .set("status",2).eq("msgId",mailLog.getMsgId()));
            }
           //如果没有超过 更新 重试次数 更新时间 重试时间
            mailLogService.update(new UpdateWrapper<MailLog>()
            .set("count",mailLog.getCount()+1)
            .set("updateTime",LocalDateTime.now())
            .set("tryTime",LocalDateTime.now().plusMinutes(MailConstants.MAX_TIMEOUT))
            .eq("msgId",mailLog.getMsgId()));

           //查询当前信息日志的 员工信息
            Employee employee = employeeService
                    .getAllEmployee(mailLog.getEid()).get(0);
            //发送 信息
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,
                    MailConstants.MAIL_ROUTINGKEY_NAME,
                    employee,
                    new CorrelationData(mailLog.getMsgId()));

        });

    }

}
